package com.atguigu.seckill.scheduled;

import com.atguigu.seckill.service.SeckillService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/** 定时任务，定时将三天之内的秒杀活动
 *  商品 保存到redis中，
 * @Author ShiJieLin
 * @Date 2022/5/3 16:37
 * @Version 1.0
 */
@Component
@Slf4j
public class SeckillScheduled {

    @Autowired
    private SeckillService seckillService;
    @Autowired
    private RedissonClient redissonClient;
    //秒杀商品上架功能的锁
    private final String upload_lock = "seckill:upload:lock";

    /** 定时任务，将近三天秒杀活动的相关信息和商品
     *  进行上架到redis中，考虑是分布式，所以要加
     *  分布式锁，保障接口的幂等性
     *   @Scheduled(cron = "*\n/3 * * * * ? ")
     *   @Scheduled(cron = "0 0 1/1 * * ? ")
     */
    @Scheduled(cron = "0 0 1/1 * * ? ")
    public void uploadSeckillSkuLatest3Days() {
        // 1.重复上架无需处理
        log.info("上架秒杀的商品...");

        RLock lock = redissonClient.getLock(upload_lock);

        try{

            lock.lock(10, TimeUnit.SECONDS);
            seckillService.uploadSeckillSkuLatest3Days();
        }finally {
            lock.unlock();
        }



    }



}
